<template>
  <div id="app" class="ucenterPage">
    <h1 class="uc-title">账号设置</h1>
    <div class="uc-file-list">
      <el-collapse accordion class="custom-collapse">
        <!-- 个人资料 -->
        <el-collapse-item>
          <template slot="title">
            <div class="collapse-title">
              <b>个人资料</b>
              <div class="collapse-title-r">{{user.name}}</div>
            </div>
          </template>
          <div class="collapse-main">
            <el-form label-width="130px" label-position="right">
              <el-form-item label="姓名：">
                <el-input v-model="user.name" placeholder></el-input>
              </el-form-item>
              <el-form-item label="所在城市：">
                <el-cascader
                  size="large"
                  :options="options"
                  v-model="selectedOptions"
                  @change="handleChange"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="性别：">
                <el-radio v-model="user.sex" :label="Number(0)">男</el-radio>
                <el-radio v-model="user.sex" :label="Number(1)">女</el-radio>
              </el-form-item>
              <el-form-item label="生日：">
                <el-date-picker v-model="user.birthday" type="date" placeholder="选择出生日期"></el-date-picker>
                <small class="help-text">（该信息其他人不可见）</small>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="updateUser">保存</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-collapse-item>

        <!-- 头像 -->
        <el-collapse-item>
          <template slot="title">
            <div class="collapse-title">
              <b>头像</b>
              <div class="collapse-title-r">
                <div class="user-tr-image">
                  <img v-if="user.avatar" width="50" height="50" :src="user.avatar" />
                  <img
                    v-if="!user.avatar"
                    width="50"
                    height="50"
                    src="@/assets/images/default-user-img.png"
                  />
                </div>
              </div>
            </div>
          </template>
          <div class="collapse-main">
            <div class="ucenter-user-file-image">
              <el-image style="width: 120px; height: 120px;border-radius:50%;overflow:hidden;">
                <!-- 默认图片 -->
                <div slot="error" class="image-slot" @click="centerDialogVisible = true">
                  <img v-if="user.avatar" width="120" height="120" :src="user.avatar" />
                  <img
                    v-if="!user.avatar"
                    width="120"
                    height="120"
                    src="@/assets/images/default-user-img.png"
                  />
                </div>
              </el-image>
              <el-button
                class="ucenter-upload-img-btn"
                size="small"
                @click="centerDialogVisible = true"
              >上传头像</el-button>
            </div>
          </div>
        </el-collapse-item>

        <!-- 登录邮箱 -->
        <el-collapse-item>
          <template slot="title">
            <div class="collapse-title">
              <b>登录邮箱</b>
              <div class="collapse-title-r">{{user.email?user.email:'未绑定'}}</div>
            </div>
          </template>
          <div class="collapse-main">
            <el-form label-width="130px" label-position="right" :model="user" :rules="rulesMail" ref="user">
              <el-form-item label="新邮箱：" prop="email">
                <el-input type="email" v-model="user.email" placeholder></el-input>
              </el-form-item>
              <el-form-item style="magin-top:20px;">
                <el-button>取消</el-button>
                <el-button type="primary" @click="updateUser">确定</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-collapse-item>

        <!-- 绑定手机 -->
        <el-collapse-item>
          <template slot="title">
            <div class="collapse-title">
              <b>绑定手机</b>
              <div class="collapse-title-r">{{user.telephone}}</div>
            </div>
          </template>
          <div class="collapse-main">
            <el-form v-if="!show" label-width="130px" label-position="right">
              <el-form-item label="原密码：">
                <el-input type="password" v-model="oldpwd1"></el-input>
              </el-form-item>
              <el-form-item label="手机号码：">
                <el-input type v-model="phone"></el-input>
              </el-form-item>
              <el-form-item label="手机验证码：">
                <el-input type="text" v-model="smsCode"></el-input>
                <el-button @click="sendSms">获取验证码</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="updatePhone">绑定</el-button>
              </el-form-item>
            </el-form>
            <el-form v-if="show" label-width="130px" label-position="right">
              <el-form-item label="已绑定手机：">
                {{user.telephone}}
                <i
                  style="font-size:24px;color:#999;vertical-align: middle;"
                  class="el-icon-success"
                ></i>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="show = !show">更换手机号</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-collapse-item>

        <!-- 密码 -->
        <el-collapse-item>
          <template slot="title">
            <div class="collapse-title">
              <b>密码</b>
              <div class="collapse-title-r">········</div>
            </div>
          </template>
          <div class="collapse-main">
            <el-form label-width="130px" label-position="right">
              <el-form-item label="当前密码：">
                <el-input type="password" v-model="oldPassword"></el-input>
              </el-form-item>
              <el-form-item label="新密码：">
                <el-input type="password" v-model="newpassword"></el-input>
              </el-form-item>
              <el-form-item label="确认密码：">
                <el-input type="password" v-model="newpassword1"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="updatePassword">保存</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled>
          <template slot="title">
            <div class="collapse-title">
              <b>角色</b>
              <div class="collapse-title-r">{{user.roleName}}</div>
            </div>
          </template>
        </el-collapse-item>
        <el-collapse-item disabled>
          <template slot="title">
            <div class="collapse-title">
              <b>岗位</b>
              <div class="collapse-title-r">{{user.jobPosition}}</div>
            </div>
          </template>
        </el-collapse-item>
        <el-collapse-item disabled>
          <template slot="title">
            <div class="collapse-title">
              <b>上级</b>
              <div class="collapse-title-r">{{user.parentName}}</div>
            </div>
          </template>
        </el-collapse-item>
        <el-collapse-item disabled>
          <template slot="title">
            <div class="collapse-title">
              <b>所属部门</b>
              <div class="collapse-title-r">{{user.deptName}}</div>
            </div>
          </template>
        </el-collapse-item>
        <el-collapse-item disabled>
          <template slot="title">
            <div class="collapse-title">
              <b>入职时间</b>
              <div class="collapse-title-r">{{user.entryDate}}</div>
            </div>
          </template>
        </el-collapse-item>
        <el-collapse-item disabled>
          <template slot="title">
            <div class="collapse-title">
              <b>在职状态</b>
              <div class="collapse-title-r">{{user.status==0?'在职':'离职'}}</div>
            </div>
          </template>
        </el-collapse-item>
      </el-collapse>
    </div>

    <!-- 上传头像 -->
    <el-dialog
      title="上传头像"
      :visible.sync="centerDialogVisible"
      class="custom-dialog userImageUpload"
      width="480px"
      center
    >
      <div class="user-img-upload">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img width="220" height="220" v-if="avatar " :src="avatar" class="avatar" />
          <span v-else>
            <i class="el-icon-plus avatar-uploader-icon"></i>
            <p>选择图片</p>
            <p>只支持JPG/PNG/GIF，GIF文件</p>
            <p>建议尺寸240x240</p>
          </span>
        </el-upload>
        <p>点击图片重新上传修改头像</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="centerDialogVisible = false">取 消</el-button> -->
        <el-button type="primary" @click="setUserAvatar">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 上传头像结束 -->
  </div>
</template>

<script>
import Http from "@/libs/http.js";
import {
  provinceAndCityData,
  CodeToText,
  TextToCode
} from "element-china-area-data";
export default {
  name: "ucenter",
  data() {
    const validateEmail = (rule, value, callback) => {
      let regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (value === "") {
        callback(new Error("邮箱不能为空"));
      } else if (!regEmail.test(value)) {
        callback(new Error("请输入正确的邮箱"));
      } else {
        callback();
      }
    };
    return {
      phone: "",
      oldpwd1: "",
      smsCode: "",
      avatar: "",
      userId: JSON.parse(localStorage.user).user.id,
      roles: JSON.parse(localStorage.user).roles,
      centerDialogVisible: false,
      uploadUrl: process.env.BASE_API + "/user/upload",
      options: provinceAndCityData,
      user: {
        roleIds: ["1", "2"],
        sex: "",
        name: "",
        jobPosition: "",
        entryDate: null,
        sexual: [
          {
            female: true,
            male: false
          }
        ],
        depid: "",
        loginName: "",
        password: "",
        idCard: "",
        email: "",
        telephone: "",
        parentId: "",
        status: ""
      },
      rulesMail: {
        email: [{ validator: validateEmail, trigger: "blur" }]
      },
      oldPassword: "",
      newpassword: "",
      newpassword1: "",
      selectedOptions: ["130100"],
      show: false
    };
  },
  created() {
    this.init();
  },
  methods: {
    init: function() {
      Http.api
        .get("user/" + JSON.parse(localStorage.user).user.id)
        .then(res => {
          this.user = res.data;
          this.avatar = this.user.avatar;
        });
    },
    // 图片上传
    handleAvatarSuccess(res, file) {
      this.avatar = res.url;
    },
    setUserAvatar() {
      this.centerDialogVisible = false;
      this.user.avatar = this.avatar;
      this.updateUser();
    },
    beforeAvatarUpload(file) {
      var fileTypes = ["image/jpeg", "image/png", "image/gif"];
      const isJPG = fileTypes.indexOf(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (isJPG == -1) {
        this.$message.error("只支持JPG/PNG/GIF文件!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleChange(res) {
      // this.policyAddr.addr.provinceName = CodeToText[res[0]];
      this.user.city = CodeToText[res[1]];
      this.user.cityCode = res[1];
      if (this.user.city === "市辖区") {
        this.user.city = CodeToText[res[0]];
      }
      console.log(this.user);
    },
    updateUser(name) {
      this.$refs['user'].validate(valid => {
        if (valid) {
          Http.api.put("/user/" + this.userId, this.user).then(res => {
            this.$message.success("保存成功");
            let user = JSON.parse(localStorage.user);
            user.user.name = this.user.name;
            user.user.avatar = this.user.avatar;
            localStorage.user = JSON.stringify(user);
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    sendSms() {
      if (this.phone && this.oldpwd1) {
        Http.api.post(
          "code/sms2?phone=" + this.phone + "&password=" + this.oldpwd1
        );
      } else {
        this.$message.error("请输入手机号和密码");
      }
    },
    updatePhone() {
      if (this.phone && this.oldpwd1) {
        Http.api
          .put("user/phone?phone=" + this.phone + "&code=" + this.smsCode)
          .then(() => {
            this.$message.success("手机绑定成功");
            this.show = !this.show;
            this.user.telephone = this.phone;
          });
      } else {
        this.$message.error("请输入手机号和密码");
      }
    },

    updatePassword() {
      if (this.newpassword1 === "") {
        this.$message.error("请输入新密码");
        return;
      }
      if (this.newpassword != this.newpassword1) {
        this.$message.error("两次密码不一致");
        return;
      }
      Http.api
        .put("/user/password", {
          password: this.newpassword,
          oldPassword: this.oldPassword
        })
        .then(() => {
          this.$message.success("密码已修改");
        });
    }
  }
};
</script>

